//备注：拷贝代码请加上作者信息
//作者：王海涛
//邮箱：1126471088@qq.com
//版本：V1.0.0
#include "bkp_bsp.h"
#include <string.h>

/*BKP 启动*/
static void WHT_BKP_BSP_Start(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);//open BKP PWR clock
}
/*BKP复位*/
static void WHT_BKP_BSP_Reset(void)
{
	RCC_BackupResetCmd(ENABLE);
	RCC_BackupResetCmd(DISABLE);
}
/*BKP读取到用户缓存里*/
static void WHT_BKP_BSP_Read(unsigned char start_pos, unsigned char count, unsigned char* buffer)
{
	char i = 0;
	unsigned char BKP_DR_Count = (start_pos + count) / 4;

	if ((start_pos + count) > WHT_BKP_BSP_DATA_SIZE)
		return;
	
	unsigned int BKP_BSP_DR_Buffer[BKP_DR_Count];
	for (char BKP_DR_Number = start_pos / 4; BKP_DR_Number < BKP_DR_Count; BKP_DR_Number++)
	{
		BKP_BSP_DR_Buffer[i++] = RTC_ReadBackupRegister(BKP_DR_Number);
	}
	memcpy(buffer, ((unsigned char*)BKP_BSP_DR_Buffer) + start_pos % 4, count);
}
/*BKP写入用户缓存数据*/
static void WHT_BKP_BSP_Write(unsigned char start_pos, unsigned char count, const unsigned char* buffer)
{
	char i = 0;
	unsigned char BKP_DR_Count = (start_pos + count) / 4;

	if ((start_pos + count) > WHT_BKP_BSP_DATA_SIZE)
		return;
	
	unsigned int BKP_BSP_DR_Buffer[BKP_DR_Count];
	for (char BKP_DR_Number = start_pos / 4; BKP_DR_Number < BKP_DR_Count; BKP_DR_Number++)
	{
		BKP_BSP_DR_Buffer[i++] = RTC_ReadBackupRegister(BKP_DR_Number);
	}
	memcpy(((unsigned char*)BKP_BSP_DR_Buffer) + start_pos % 4, buffer, count);
	PWR_BackupAccessCmd(ENABLE);//open RTC & BKP registers write mode
	for (char BKP_DR_Number = start_pos / 4; BKP_DR_Number < BKP_DR_Count; BKP_DR_Number++)
	{
		RTC_WriteBackupRegister(BKP_DR_Number, BKP_BSP_DR_Buffer[i++]);
	}
	PWR_BackupAccessCmd(DISABLE);//close RTC & BKP registers write mode
}


/*全局常量*/
const WHT_BKP_BSP_t WHT_BKP_BSP =
{
	.WHT_BKP_Start = WHT_BKP_BSP_Start,
	.WHT_Reset     = WHT_BKP_BSP_Reset,
	.WHT_Read      = WHT_BKP_BSP_Read,
	.WHT_Write     = WHT_BKP_BSP_Write,
};
